package com.haixiaoke.saas.callback;

import com.alibaba.fastjson2.JSON;
import com.fasc.open.api.utils.crypt.FddCryptUtil;
import com.fasc.open.api.v5_1.res.template.SignTemplateDetailRes;
import com.fasc.open.api.v5_1.res.user.UserIdentityInfoRes;
import com.haixiaoke.saas.common.config.FaDaDaConfig;
import com.haixiaoke.saas.contract.fadada.service.FaDaDaService;
import com.haixiaoke.saas.contract.service.impl.FaDaDaCallbackService;
import com.haixiaoke.saas.system.framework.manager.AsyncManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.TimerTask;

/**
 * @Author panda
 * @Date 2024/5/27
 **/
@RestController
@RequestMapping("/callback/electronicVisa")
public class FaDaDaController {

    @Autowired
    private FaDaDaConfig faDaDaConfig;
    @Autowired
    private FaDaDaService faDaDaService;
    @Autowired
    private FaDaDaCallbackService faDaDaCallbackService;

    /**
     * 法大大电子签回调
     * <a href="https://dev.fadada.com/api-doc/DKO6NVNYH3/UMZTMGU1FSROCUQJ/5-1"/>
     */
    @ResponseBody
    @PostMapping("/fadada")
    public String fddEventCallback(@RequestHeader HttpHeaders headers,
                                   @RequestParam("bizContent") String bizContent) {
        // appSecret，由开发者登陆到法大大官网，在应用管理管理中点击应用详情里面获取
        String appSecret = faDaDaConfig.getAppSecret();
        // 获取请求头参数
        String appId = headers.getFirst("X-FASC-App-Id");
        String signType = headers.getFirst("X-FASC-Sign-Type");
        String sign = headers.getFirst("X-FASC-Sign");
        String timestamp = headers.getFirst("X-FASC-Timestamp");
        // 事件名称，开发者可以根据不同事件名称去解析bizContent的值，实现不同的逻辑
        String event = headers.getFirst("X-FASC-Event");
        String nonce = headers.getFirst("X-FASC-Nonce");
        // 验签
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("X-FASC-App-Id", appId);
        paramMap.put("X-FASC-Sign-Type", "HMAC-SHA256");
        paramMap.put("X-FASC-Timestamp", timestamp);
        paramMap.put("X-FASC-Nonce", nonce);
        paramMap.put("X-FASC-Event", event);
        paramMap.put("bizContent", bizContent);


        // 参数排序，ascii码排序
        String sortParam = FddCryptUtil.sortParameters(paramMap);
        // 生成签名后可以进行校验
        try {
            String signature = FddCryptUtil.sign(sortParam, timestamp, appSecret);
            if (!signature.equals(sign)) {
                // log.error("日志记录，签名失败");
                // 为了不重复接收该请求，建议这里返回success，返回success后这条消息法大大将中断重试回调机制
                return "{\"msg\":\"success\"}";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Map<String, Object> map = JSON.parseObject(bizContent, Map.class);

        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                faDaDaCallbackService.disposeCallback(event, map);
            }
        });
        return "{\"msg\":\"success\"}";
    }

    @GetMapping("/test")
    public SignTemplateDetailRes test(){
        return faDaDaService.getSignTemplateDetail("1718259685024158408");
    }
}
